import { defineStore } from 'pinia'

interface UserInfo {
  id: number | null
  name: string
  email: string
}

export const useUserStore = defineStore('user', {
  state: (): UserInfo => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      return JSON.parse(storedUser)
    }
    return {
      id: null,
      name: '',
      email: ''
    }
  },
  actions: {
    setUser(user: UserInfo) {
      this.id = user.id
      this.name = user.name
      this.email = user.email
      this.persistUser()
    },
    clearUser() {
      this.id = null
      this.name = ''
      this.email = ''
      localStorage.removeItem('user')
    },
    persistUser() {
      localStorage.setItem('user', JSON.stringify({
        id: this.id,
        name: this.name,
        email: this.email
      }))
    }
  },
  getters: {
    isLoggedIn(): boolean {
      return this.id !== null
    }
  }
})
